﻿using HzyScanDiService.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace HzyScanDiService.Models
{
    public class ClassContext
    {
        public Type ClassType { get; }

        public ClassContext(Type classType)
        {
            ClassType = classType;
        }

        /// <summary>
        /// 获取类名称
        /// </summary>
        /// <returns></returns>
        public string GetClassName() => ClassType.Name;

        /// <summary>
        /// 获取class 的所有函数
        /// </summary>
        /// <returns></returns>
        public List<Function> GetFunctions()
        {
            var result = new List<Function>();
            var methods = ClassType.GetMethods(BindingFlags.Instance | BindingFlags.Public)?.Where(w => w.IsVirtual);

            foreach (var method in methods)
            {

                result.Add(new Function
                {
                    Name = method.Name,
                    ParameterInfo = method.GetParameters(),
                    ResultType = method.ReturnType,
                    MethodInfo = method
                });

            }

            return result;
        }

        /// <summary>
        /// 获取AopBase特性
        /// </summary>
        /// <returns></returns>
        public AopBaseAttribute GetAopBaseAttribute()
        {
            var aopBaseAttribute = ClassType
                .GetCustomAttributes<AopBaseAttribute>()?
                .FirstOrDefault()
                ;

            return aopBaseAttribute;
        }

        /// <summary>
        /// 根据构造函数获取参数
        /// </summary>
        /// <returns></returns>
        public ParameterInfo[] GetParametersByConstructor()
        {
            return ClassType.GetConstructors()[0].GetParameters();
        }
    }

    public class Function
    {
        /// <summary>
        /// 函数名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 返回类型
        /// </summary>
        public Type ResultType { get; set; }

        /// <summary>
        /// 入参
        /// </summary>
        public ParameterInfo[] ParameterInfo { get; set; }

        /// <summary>
        /// 函数的元信息
        /// </summary>
        public MethodInfo MethodInfo { get; set; }

    }
}
